#!/usr/bin/env bash

set -o nounset
set -o errexit
set -o pipefail

STARTUP_DIR="$( cd "$( dirname "$0" )" && pwd )"

source ${STARTUP_DIR}/../settings.sh

KUBECTL="kubectl --context=${KUBE_CONTEXT}"

getUrl() {
    EXTERNAL_IP=$(${KUBECTL} get svc -n jenkins jenkins -o jsonpath='{.status.loadBalancer.ingress[0].ip}')
    NODEPORT=$(${KUBECTL} get svc -n jenkins jenkins -o jsonpath='{.spec.ports[0].nodePort}')

    url="jenkins-url-unknown"

    if [ -n "${EXTERNAL_IP}" ]
    then
          url="${EXTERNAL_IP}:8080/"
    else
          if [ -z "${KUBE_CONTEXT}" ]
          then
            KUBE_CONTEXT=$(kubectl config current-context)
          fi
          if [ "${KUBE_CONTEXT}" = "minikube" ]
          then
            EXTERNAL_IP=$(minikube ip)
          else
            EXTERNAL_IP="localhost"
          fi
          url="${EXTERNAL_IP}:${NODEPORT}/"
    fi
    echo $url
}

echo $(getUrl)